<template>
  <div class="confirm-form">
    <h1 style="color: #2c3e50"> 外来人员登记 </h1>
    <el-form :model="form" ref="confirmForm"
             label-width="auto" style="max-width: 600px;" size="large" :rules="rules">
      <el-form-item label="姓名" prop="name">
        <el-input v-model="form.name" placeholder="访客姓名"/>
      </el-form-item>
      <el-form-item label="联系方式" prop="phone">
        <el-input v-model="form.phone" placeholder="请填写座机或手机号码"/>
      </el-form-item>
      <el-form-item label="访客单位" prop="company">
        <el-input v-model="form.company" placeholder="请填写单位名称"/>
      </el-form-item>
      <el-form-item label="来访事由">
        <el-input v-model="form.message" placeholder="请填写接待人等信息"/>
      </el-form-item>
      <el-form-item>
        <div class="a">
          <el-button @click="Object.keys(form).forEach(key => form[key]='')">重置</el-button>
          <el-button type="primary" @click="showAgreementDialog">确认入场须知</el-button>
        </div>
      </el-form-item>
    </el-form>

    <!-- Dialog 弹窗 -->
    <el-dialog
        v-model="agreementDialogVisible"
        title="请确认"
        width="50%"
        :before-close="handleCancel"
        center>
      <p>您已同意以下协议内容（此处为示例，实际应展示协议详情）：</p>
      <p>协议内容...</p>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button
              type="primary"
              :disabled="!confirmButtonEnabled"
              @click="handleConfirm"
              :loading="confirmButtonLoading">
            {{ confirmButtonText }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      form: {
        name: '',
        phone: '',
        company: '',
        message: ''

      },
      rules: {
        name: [
          {required: true, message: '请输入姓名', trigger: 'blur'},
          {min: 2, max: 10, message: '姓名长度在 2 到 10 个字符', trigger: 'blur'}
        ],
        phone: [
          {required: true, message: '请输入手机号', trigger: 'blur'},
          {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur'}
        ],
        company: [
          {required: true, message: '请输入公司名称', trigger: 'blur'},
          {min: 2, max: 20, message: '公司名称长度在 2 到 20 个字符', trigger: 'blur'}]
      },
      agreementDialogVisible: false, // 控制弹窗显示与隐藏
      confirmButtonEnabled: true, // 控制确认按钮是否可点击
      confirmButtonLoading: false, // 控制确认按钮是否处于加载状态
      confirmButtonText: '确认(${this.countdown}秒)', // 确认按钮文本，初始为倒计时
      countdown: 1, // 倒计时初始值
      countdownInterval: null, // 倒计时定时器
      qrCodeUrl: ""
    };
  },
  methods: {
    showAgreementDialog() {
      this.$refs.confirmForm.validate(validate => {
        if (validate) {
          this.agreementDialogVisible = true;
          this.confirmButtonEnabled = false; // 初始时按钮可点击，但会立即进入倒计时
          this.confirmButtonLoading = false; // 按钮不处于加载状态
          this.confirmButtonText = `确认（${this.countdown}秒）`; // 设置按钮文本为倒计时

          // 开始倒计时
          this.countdownInterval = setInterval(() => {
            if (this.countdown > 0) {
              this.countdown -= 1;
              this.confirmButtonText = `确认（${this.countdown}秒）`; // 更新按钮文本
            } else {
              clearInterval(this.countdownInterval); // 清除定时器
              this.confirmButtonEnabled = true; // 倒计时结束，按钮变为可点击（虽然此时已经是可点击状态，但为了代码清晰性仍设置）
              this.confirmButtonText = '确认'; // 更新按钮文本为“确认”
            }
          }, 1000); // 每秒执行一次
        } else {
          console.log('表单验证不通过');
        }
      })

    },
    handleCancel() {
      this.agreementDialogVisible = false; // 关闭弹窗
      clearInterval(this.countdownInterval); // 清除倒计时定时器
      this.countdown = 1; // 重置倒计时
      this.qrCodeUrl = ""; // 重置二维码
    },
    handleConfirm() {
      this.qrCodeUrl = ""; // 重置二维码
      if (this.countdown > 0) {
        // 如果倒计时未结束，则不执行确认操作（这里可以根据需求处理，比如显示提示信息）
        this.$message.warning('请在倒计时结束后确认');
        return;
      }

      this.confirmButtonLoading = true; // 设置按钮为加载状态

      this.$axios.post('/api/visitors/add', this.form).then(res => {
        this.confirmButtonLoading = false; // 恢复按钮状态
        this.agreementDialogVisible = false; // 关闭弹窗
        this.$message.success('协议签订成功'); // 显示成功提示信息
        this.qrCodeUrl = '/api/visitors/getQRCode?qrCodeFilename=' + res.data.data.qr_code;
        this.$emit("getUrl", this.qrCodeUrl);
      })


    },
  },
  beforeDestroy() {
    // 在组件销毁前清除定时器，防止内存泄漏
    clearInterval(this.countdownInterval);
  },
};
</script>

<style scoped>
.dialog-footer {
  text-align: right; /* 底部按钮右对齐 */
}

.confirm-form {
  width: 70%;
}

.a {
  display: flex;
  margin-left: auto;
}
</style>